<template>
  <div class="wkDetail">
    <el-button @click="onClose" type="warning" plain icon="Close">
      关闭
    </el-button>

    <div class="title">「{{ wkDataObj.nick_name }}」提交的作业</div>
    <div v-html="wkDataObj.content" class="content"></div>
    <OtherBigFile
      :isHidden="false"
      :fileArr="wkDataObj.files"
      ref="OtherBigFileRef"
      @fileArrChange="fileArrChange"
    >
    </OtherBigFile>

    <div v-if="route.query.status == '已提交'" class="Review-work">
      <div class="rvTitle">批阅作业</div>
      <el-form
        class="rvwkCon"
        ref="workFormRef"
        :model="workFormOption"
        :rules="WorkRules"
        label-width="100px"
        size="large"
        @submit.prevent
      >
        <el-form-item label="类型：" prop="status">
          <el-radio-group v-model="workFormOption.status" class="workstyle">
            <el-radio @change="onChangeRf" border :value="1" size="large"
              >批阅打分</el-radio
            >
            <el-radio @change="onChangeBack" border :value="2" size="large"
              >驳回重做</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="scoreisShow" label="成绩：" prop="fraction">
          <el-input
            v-model.trim="workFormOption.fraction"
            placeholder="请输入成绩得分"
          />
        </el-form-item>

        <el-form-item prop="content" label="批阅评语">
          <PubEditor
            :wangEditReadOnly="wangEditReadOnly"
            :editContent="workFormOption.content"
            @editContentEnv="editContentEnv"
            @imgUrlEnv="imgUrlEnv"
            @videoUrlEnv="videoUrlEnv"
            placeholder="请认真填写批阅评语..."
          >
          </PubEditor>
        </el-form-item>

        <el-form-item v-if="route.query.status == '已提交'">
          <div class="btngroup">
            <el-button type="primary" @click="submitForm"> 提交 </el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="Review-work">
      <div class="rvTitle">批阅记录</div>

      <div class="content">
        <!-- 
                <div v-for="item in reviewArr" class="collItem">

                    <el-tag v-if="item.status == 1" style="margin-right: 10px;" type="danger">驳回</el-tag>

                    <el-tag v-if="item.status == 0" style="margin-right: 10px;" type="success">通过</el-tag>
                    {{ parseTime(item.time) }}批阅

                    <div>
                        {{ item.content }}
                    </div>

                </div> -->

        <el-collapse @change="handleChange">
          <el-collapse-item v-for="item in reviewArr" class="collItem">
            <template #title>
              <el-tag
                v-if="item.status == 1"
                style="margin-right: 10px"
                type="danger"
                >驳回</el-tag
              >

              <el-tag
                v-if="item.status == 0"
                style="margin-right: 10px"
                type="success"
                >通过</el-tag
              >
              {{ parseTime(item.time) }}批阅
            </template>
            <div v-html="item.remark">
            
            </div>
          </el-collapse-item>
        </el-collapse>


      </div>
    </div>
  </div>
</template>



<script setup>
import { ref } from "vue";
import PubEditor from "@/components/PubEditor/index.vue";
import { giveEllipsisStr, getTagState, parseTime } from "@/utils/common";
import { stusubDetail, subreView, reviewRecord } from "@/api/banke/zuoye";
import { useRoute } from "vue-router";
import OtherBigFile from "@/components/OtherBigFile/index.vue";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const scoreisShow = ref(true);
const wkDataObj = ref({});
const wangEditReadOnly = ref(route.query.status == 1 ? true : false);
//作业表结构
const workFormOption = ref({
  fraction: "", //成绩
  content: "", //富文本内容
  status: 1, //批阅类型（1/2）
});
//表结构验证规则
const WorkRules = ref({
  status: [
    {
      required: true,
      message: "类型必须选择",
      trigger: "blur",
    },
  ],
  fraction: [{ required: true, message: "成绩必须填写", trigger: "blur" }],
  content: [{ required: true, message: "批阅评语必须填写", trigger: "blur" }],
});

// 批阅记录数据
const reviewArr = ref([]);
// 附件内容改变
const fileArrChange = (e) => {
  wkDataObj.value.files = e;
};

// 获取上传图像成功的Url
const imgUrlEnv = (e) => {
  imgUrlArr.value.push(e);
};

// 获取上传视频成功的url

const videoUrlEnv = (e) => {
  videoUrlArr.value.push(e);
};
//获取富文本返回的内容
const editContentEnv = (e) => {
  if (e == "<p><br></p>") {
    e = "";
  }

  if (workFormOption.value.content) {
    proxy.$refs["workFormRef"].clearValidate(["content"]);
  }

  workFormOption.value.content = e;
  // 将上传成功的图像和视频的[file_id: ${res.file_id},url: ${tem_url.value}]地址分别放在alt和poster属性中
  let imgregex = /alt="(.*?)"/g;
  let imgmatches = e.match(imgregex);
  let videoregex = /poster="(.*?)"/g;
  let videomatches = e.match(videoregex);
  if (imgmatches) {
    imgmatches.forEach(function (match, index) {
      workFormOption.value.content = e.replace(
        match,
        `alt="${imgUrlArr.value[index]}"`
      );
    });
  }
  if (videomatches) {
    videomatches.forEach(function (match, index) {
      workFormOption.value.content = e.replace(
        match,
        `poster="${videoUrlArr.value[index]}"`
      );
    });
  }
};

// 重置批阅作业
const resetForm = () => {
  proxy.$refs.workFormRef.resetFields();
};

// 选中批阅打分的事件
const onChangeRf = () => {
  // console.log(666);
  scoreisShow.value = true;
};

// 选中驳回重做的事件
const onChangeBack = () => {
  // console.log(666);
  scoreisShow.value = false;
};

const onClose = () => {
  proxy.$tab.closePage(route).then((res) => {
    router.back();
  });
};
//获取详情内容
const getDetailCon = () => {
  stusubDetail(route.query.id).then((res) => {
    console.log(res);
    wkDataObj.value = res;
    // 回显图像和视频
    wkDataObj.value.content = wkDataObj.value.content.replace(
      /\[file_id: (\d+),url: (.+?\.(jpg|png|webp|svg|gif).*?)\]/g,
      '<img src="$2" alt="[file_id: $1,url: $2]"/>'
    );

    wkDataObj.value.content = wkDataObj.value.content.replace(
      /<div data-w-e-type="video" data-w-e-is-void>\s*\[file_id:\s*(\d+),url:\s*([^[\]]+)\]\s*<\/div>/g,
      '<video controls src="$2"></video>'
    );
    // // 去除多余的符号
    wkDataObj.value.content = wkDataObj.value.content.replace(
      />" data-href="?" style="?"\//g,
      ""
    );



    console.log(wkDataObj.value.content);

    // 处理图像回显问题
    const processString = (str) => {
      // 处理 img 标签的 src 替换为 alt 中的 url
      const processedImgStr = str.replace(
        /<img[^>]*alt="\[file_id:[^,]*,url: ([^"]*)"[^>]*>/g,
        (match, url) => {
          return match.replace(
            /src="[^"]*"/,
            `src="${url.replace(/\]/g, "")}"`
          );
        }
      );

      // 处理 video 标签中的 source 标签的 src 替换为 poster 中的 url
      const processedVideoStr = processedImgStr.replace(
        /<video[^>]*poster="\[file_id:[^,]*,url: ([^"]*)"[^>]*>.*?<source[^>]*src="[^"]*"[^>]*>/g,
        (match, url) => {
          return match.replace(
            /<source[^>]*src="[^"]*"/,
            `<source src="${url.replace(/\]/g, "")}"`
          );
        }
      );

      return processedVideoStr;
    };

    wkDataObj.value.content = processString(wkDataObj.value.content);
  });
};

// 提交批阅
const submitForm = () => {
  console.log(workFormOption.value.content);

  proxy.$refs.workFormRef.validate((valid) => {
    if (valid) {
      workFormOption.value.id = route.query.id;
      workFormOption.value.fraction = Number(workFormOption.value.fraction);

      console.log(workFormOption.value);

      subreView(workFormOption.value).then((res) => {
        if (!res) {
          ElMessage.success("批阅成功");
          // proxy.$refs.workFormRef.resetFields()
          // 关闭当前页，返回上一页
          proxy.$tab.closePage(route).then((res) => {
            router.back();
          });
          getreviewRecord();
        } else {
          ElMessage.error(res.response.data);
        }
      });
    }
  });
};

// 获取批阅记录
const getreviewRecord = () => {
  reviewRecord(route.query.id).then((res) => {
    console.log(res);
    reviewArr.value = res;
  });
};

getreviewRecord();
getDetailCon();
</script>

<style lang="scss" scoped>
.title {
  height: 50px;
  background: #f8f8f9;
  line-height: 60px;
  text-align: center;
  margin: 20px 0;
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.rvTitle {
  height: 50px;
  background: #f8f8f9;
  line-height: 60px;
  text-align: center;
  margin: 50px 0 30px 0;
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.content {
  font-size: 14px;
  line-height: 1.7em;
  width: 80%;
  margin: 0 auto;
  
}

.Review-work {
  .rvwkCon {
    width: 80%;
    margin: 0 auto;
  }
}

.collItem {
  line-height: 60px;
//   border-top: 1px solid #eee;
}
</style>